package com.example.service.impl;

import com.example.common.BaseResponse;
import com.example.common.ErrorCode;
import com.example.exception.BusinessException;
import com.example.mapper.UserMapper;
import com.example.model.user.EditPersonalInfo;
import com.example.model.user.UpdatePassword;
import com.example.model.user.User;
import com.example.model.user.UserUpdateRequest;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.example.contant.UserConstant.*;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private static final String sALT = "luom";

    @Resource
    private UserMapper userMapper;

    //登录
    @Override
    public User userLogin(String userName, String userPassword, HttpServletRequest request) {
        //1.校验
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userName.length() < 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        //用户名不能包含特殊字符
        String vailPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vailPattern).matcher(userName);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名包含特殊字符");
        }
        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((sALT + userPassword).getBytes());

        //查询用户是否存在
        User user = userMapper.getByNameAndPassword(userName, newPassword);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或密码错误");
        }
        if (user.getUserStatus() == 1) {
            throw new BusinessException(ErrorCode.NO_AUTH, "账号不正常,请联系管理员");
        }
        //3.脱敏
        User safeUser = getSafetUser(user);
        //4.记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE, safeUser);

        return safeUser;
    }

    //脱敏处理
    @Override
    public User getSafetUser(User user) {
        if (user == null)
            return null;
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setUsername(user.getUsername());
        safeUser.setGender(user.getGender());
        safeUser.setUserRole(user.getUserRole());
        safeUser.setUserStatus(user.getUserStatus());
        safeUser.setPhone(user.getPhone());
        safeUser.setCreateTime(user.getCreateTime());
        return safeUser;
    }

    //用户注册
    @Override
    public Long userRegister(String userName, String userPassword, String checkPassword) {
        //1.校验
        if (StringUtils.isAnyBlank(userName, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userName.length() < 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        //用户名不能包含特殊字符
        String vailPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vailPattern).matcher(userName);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名包含特殊字符");
        }
        //密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不相同");
        }
        //用户名不能重复
        String name = userMapper.getByUsername(userName);
        if (name != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名重复");
        }

        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((sALT + userPassword).getBytes());

        //3.插入数据
        User user = new User();
        user.setUsername(userName);
        user.setUserPassword(newPassword);
        userMapper.save(user);
        return user.getId();
    }

    //根据id查询用户
    @Override
    public User getById(Long id) {
        User user = userMapper.getById(id);
        user = getSafetUser(user);
        return user;
    }

    //退出登录
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    //获取全部用户
    @Override
    public List<User> getUserList() {
        List<User> userList = userMapper.getUserList();
        userList.stream().map(user -> {
            getSafetUser(user);
            return user;
        }).collect(Collectors.toList());
        return userList;
    }

    @Override
    public List<User> getUserByName(String username) {
        List<User> userList = userMapper.getUserByName("%" + username + "%");
        userList.stream().map(user -> {
            getSafetUser(user);
            return user;
        }).collect(Collectors.toList());
        return userList;
    }

    @Override
    public Boolean updateUser(UserUpdateRequest userUpdateRequest) {
        //1.校验参数
        if (userUpdateRequest.getId() == SUPER_ADMIN_ID&&userUpdateRequest.getUserRole()!=SUPER_ADMIN_ROLE) {
            throw new BusinessException(ErrorCode.NO_AUTH,"超级管理员权限不能修改");
        }
        //2.更新
        return userMapper.updateUser(userUpdateRequest);
    }

    @Override
    public Boolean deleteUser(Long id) {
        return userMapper.deleteUser(id);
    }

    /**
     * 编辑个人信息
     *
     * @param personalInfo 个人信息
     * @return 是否成功
     */
    @Override
    public Boolean updateInfo(EditPersonalInfo personalInfo) {
        String userName = personalInfo.getUsername();
        //1.校验
        if (userName.length() < 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名过短");
        }
        //用户名不能包含特殊字符
        String vailPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vailPattern).matcher(userName);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名包含特殊字符");
        }

        //用户名不能重复
        User olduser = userMapper.getById(personalInfo.getId());
        if (!Objects.equals(olduser.getUsername(), userName)) {
            String name = userMapper.getByUsername(userName);
            if (name != null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名重复");
            }
        }

        //3.插入数据
        return userMapper.updateInfo(personalInfo);
    }

    //修改密码
    @Override
    public Boolean updatePassword(UpdatePassword updatePassword) {
        String userPassword=updatePassword.getUserPassword();
        String checkPassword=updatePassword.getCheckPassword();
        // 判断密码是否填写且长度符合要求
        if (userPassword == null || userPassword.isEmpty() || checkPassword == null || checkPassword.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码或校验密码未填写");
        }

        // 判断密码长度是否都大于或等于8个字符
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }

        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入密码不相同");
        }
        Long id=updatePassword.getId();
        //加密
        String newPassword = DigestUtils.md5DigestAsHex((sALT + userPassword).getBytes());
        return userMapper.updatePassword(id,newPassword);
    }

    //重置密码
    @Override
    public Boolean resetPassword(Long id) {
        String newPasswordStr="12345678";
        String newPassword = DigestUtils.md5DigestAsHex((sALT + newPasswordStr).getBytes());
        return userMapper.resetPassword(id,newPassword);
    }
}
